<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/4/6
 * Email: <939369942@qq.com>
 */
namespace basic\base;

use think\facade\Config;

abstract class BaseUpload extends BaseStorage
{

    /**
     * 文件信息
     * @var
     */
    protected $fileInfo;

    /**
     * 文件验证
     * @var
     */
    protected $validate;

    /**
     * 文件保存路径
     * @var
     */
    protected $path;

    /**
     * 驱动名称
     * @var string
     */
    protected $name;


    protected function init(array $config)
    {
        $this->fileInfo = new \stdClass();
        $this->validateStatus();
    }

    /**
     * 文件上传路径
     * @param $path
     * @return $this
     * User: xiest
     * Date: 2021/4/6
     */
    public function toPath($path)
    {
        $this->path = $path;
        return $this;
    }

    /**
     * 文件信息
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    public function fileInfo()
    {
        return $this->fileInfo;
    }

    /**
     * 存储文件名
     * @param string $ext
     * @return string
     * User: xiest
     * Date: 2021/4/6
     */
    public function getName(string $ext = 'jpg')
    {
        return date('YmdHis').rand(0,99999).substr(md5(uniqid()),0,6).rand(0,999999).".{$ext}";
    }


    /**
     * 获取相关配置
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    public function getConfig()
    {
        $config = Config::get($this->configFile . '.stores.' . $this->name, []);
        if (empty($config)) {
            $config['filesize'] = Config::get($this->configFile . '.filesize', []);
            $config['fileExt'] = Config::get($this->configFile . '.fileExt', []);
            $config['fileMime'] = Config::get($this->configFile . '.fileMime', []);
        }
        return $config;
    }

    /**
     * 设置验证规则
     * @param null $validate
     * User: xiest
     * Date: 2021/4/6
     */
    public function setValidate($validate = null)
    {
        if(is_null($validate))
        {
            $validate =$this->getConfig();
        }
        $rule = [];
        foreach ($validate as $k=>$v)
        {
            $rule[] = $k.':'.(is_array($v)?join(',',$v):$v);
        }
        $this->validate =implode('|',$rule);
    }


    /** 是否验证
     * @param bool $status
     * @return $this
     * User: xiest
     * Date: 2021/4/6
     */
    public function validateStatus($status = true){
        if($status)
            $this->setValidate();
        else
            $this->validate = '';
        return $this;
    }

    /**
     * 获取文件类型和大小
     * @param string $url
     * @param bool $isData
     * @return array
     */
    protected function getFileHeaders(string $url, $isData = true)
    {
        stream_context_set_default(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]);
        $header['size'] = 0;
        $header['type'] = 'image/jpeg';
        if (!$isData) {
            return $header;
        }
        try {
            $headerArray = get_headers(str_replace('\\', '/', $url), true);
            if (!isset($headerArray['Content-Length'])) {
                $header['size'] = 0;
            }
            if (!isset($headerArray['Content-Type'])) {
                $header['type'] = 'image/jpeg';
            }
            if (is_array($headerArray['Content-Length']) && count($headerArray['Content-Length']) == 2) {
                $header['size'] = $headerArray['Content-Length'][1];
            }
            if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) {
                $header['type'] = $headerArray['Content-Type'][1];
            }
        } catch (\Exception $e) {
        }
        return $header;
    }

    /**
     * 获取上传信息
     * @return array
     */
    public function getUploadInfo()
    {
        if (isset($this->fileInfo->filePath)) {
            if (strstr($this->fileInfo->filePath, 'http') === false) {
                $url = request()->domain() . $this->fileInfo->filePath;
            } else {
                $url = $this->fileInfo->filePath;
            }
             // $headers = $this->getFileHeaders($url);
            return [
                'name' => $this->fileInfo->fileName,
                'real_name' => $this->fileInfo->realName ?? '',
                //'size' => $headers['size'] ?? 0,
                // 'type' => $headers['type'] ?? 'image/jpeg',
                'dir' => $this->fileInfo->filePath,
                'thumb_path' => $this->fileInfo->filePath,
                'time' => time(),
            ];
        } else {
            return [];
        }
    }



    /**
     * 初始化
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    abstract public function app();


    /**
     * 上传文件
     * @param string $file
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    abstract public function move(string $file = 'file');


    /**
     * 移除文件
     * @param string $key
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    abstract public function remove(string $key);


    /**
     * 获得秘钥
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    abstract public function getKeys();

    /**
     * 文件流上传
     * @param $content
     * @param $key
     * @return mixed
     * User: xiest
     * Date: 2021/4/6
     */
    abstract public function stream($content,$key);

}